import re
from apps.users.utils.jwt_token import get_token
from rest_framework import serializers
from apps.users.models import User
from django_redis import get_redis_connection


class RegisterSerializer(serializers.ModelSerializer):
    # 注册序列化器
    token = serializers.CharField(read_only=True)
    sms_code = serializers.CharField(write_only=True)
    username = serializers.CharField(min_length=5, max_length=20, label='用户名')

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'sms_code', 'token', 'avatar')
        extra_kwargs = {
            'password': {'write_only': True, 'min_length': 6, 'max_length': 20},
            'avatar': {'read_only': True},
        }

    # def validate_mobile(self, value):
    #     if not re.match(r'^1[3-9]\d{9}$', value):
    #         raise serializers.ValidationError('手机号格式错误')

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('手机号格式错误')
        # 校验短信验证码
        sms_code = attrs.get('sms_code')
        # 连接redis
        redis_conn = get_redis_connection('verify')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            raise serializers.ValidationError('验证码过期')
        if sms_code != sms_code_server.decode():
            raise serializers.ValidationError('验证码错误')

        return attrs

    def create(self, validated_data):

        del validated_data['sms_code']

        user = User.objects.create_user(**validated_data)
        token = get_token(user)

        user.token = token
        return user


class LoginSerializer(serializers.ModelSerializer):
    '''登录序列化器'''
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('username', 'password', 'mobile', 'id', 'token', 'avatar')

    def validate(self, attrs):
        mobile = attrs.get('username')
        password = attrs.get('password')

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            raise serializers.ValidationError('无数据')
        if not user.check_password(password):
            raise serializers.ValidationError('用户名或密码错误')

        attrs['user'] = user

        return attrs

    def create(self, validated_data):
        user = validated_data.get('user')

        token = get_token(user)
        user.token = token

        return user

